<!--
 * @Description: 原物料结算
 * @Autor: wangwangwang
 * @Date: 2021-03-25 09:21:19
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-03-26 19:27:27
-->
<template>
  <div class="pages_content table">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main>
        <!-- 导航 -->
        <div class="tabtop">
          <div v-for="(item, index) in navlist" :key="index" @click="choose(item.id)">
            <div :class="currenindex == index + 1 ? 'active' : 'text'">{{ item.value }}</div>
            <div v-if="currenindex !== index + 1 && currenindex !== index + 2 && index !== 2" class="hr"></div>
          </div>
        </div>
        <!-- 搜索条件 -->
        <div>
          <div class="header_right" @click="showCardNav = !showCardNav">
            <div class="title">搜索</div>
            <div>
              <transition name="from"></transition>
              <span v-show="!showCardNav">
                <i style="margin-right: 5px" class="el-icon-arrow-down"></i>
              </span>
              <transition name="to"></transition>
              <span v-show="showCardNav">
                <i style="margin-right: 5px" class="el-icon-arrow-up"></i>
              </span>
            </div>
          </div>
          <div v-show="showCardNav" class="hr"></div>
          <el-collapse-transition>
            <div v-show="showCardNav" style="padding-top:18px">
              <el-form v-if="currenindex!==3" :inline="true" label-width="110px">
                <el-form-item>
                  <span slot="label">供应商</span>
                  <div v-if="currenindex==1" style="width:240px;height:36px;display:flex;">
                    <div :title="searchText" style="width:180px;padding:0 10px;border-bottom: 1px solid #bbb;margin-right:5px;" class="ellipsis">{{searchText}}</div>
                    <el-button class="bottom_all_two" @click="getsearchData(),search=true">选择</el-button>
                  </div>
                  <el-select v-if="currenindex==2" v-model="tableParam.contractId" placeholder="请选择">
                    <el-option v-for="(item, index) in contractId" :key="index" :label="item.supplier" :value="item.supplierId"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item v-if="currenindex==1">
                  <span slot="label">原物料类型</span>
                  <el-select ref="rawType" v-model="tableParam.rawTypeId" placeholder="请选择" style="width:130px;" @change="$nextTick(()=>{tableParam.rawType = $refs.rawType.selectedLabel})">
                    <el-option v-for="item in typelist" :key="item.id" :label="item.itemName" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <span slot="label">结算时间段</span>
                  <el-date-picker v-model="datePicker" style="height:36px" type="datetimerange" unlink-panels align="right" start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button icon="el-icon-search" size="medium" class="bottom_all" @click="(tableParam.page = 1), pagesgettableData()">查 询</el-button>
                  <el-button v-if="currenindex!=1" size="medium" class="bottom_all_two" style="margin-left: 12px" @click="init()">重 置</el-button>
                </el-form-item>
              </el-form>
              <el-form v-if="currenindex==3" :inline="true" label-width="110px">
                <el-form-item>
                  <span slot="label">结算单编号</span>
                  <el-input v-model="tableParam.statementNo" placeholder="请输入" clearable></el-input>
                </el-form-item>
                <el-form-item>
                  <span slot="label">供应商</span>
                  <el-select v-model="tableParam.supplierId" placeholder="请选择">
                    <el-option v-for="(item, index) in searchData" :key="index" :label="item.supplier" :value="item.supplierId"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button icon="el-icon-search" size="medium" class="bottom_all" @click="(tableParam.page = 1), gettableData()">查 询</el-button>
                  <el-button size="medium" class="bottom_all_two" style="margin-left: 12px" @click="init()">重 置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-collapse-transition>
          <div class="hr"></div>
          <div class="card" :style="currenindex!==1?'padding-top:10px':''">
            <div v-show="currenindex==1" class=" card_nav">
              <div>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='SHENGCJSD'))!==-1" size="small" class="bottom_three" :disabled="generate.logisticsList.length==0" @click="statements">
                  生成结算单
                </el-button>
              </div>
              <div>
              </div>
            </div>
            <div v-loading="tableLoading" class="card_info" :style="style">
              <el-table ref="table" :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="tableData" tooltip-effect="dark" @selection-change="pageshandleSelectionChange">
                <el-table-column v-if="currenindex==1" align="center" type="selection"></el-table-column>
                <template v-for="(item, index2) in table">
                  <el-table-column v-if="item.status" :key="index2" :label="item.label" align="center" :min-width="item.width" :fixed="item.label =='操作'?'right':false">
                    <template slot-scope="scope">
                      <span v-if="item.label == '结算时间段'">
                        {{scope.row.startTime}}至{{scope.row.endTime}}
                      </span>
                      <div v-else-if="item.label == '结算单编号'" class="table_link" @click="show(scope.row)">
                        {{ scope.row[item.prop] }}
                      </div>
                      <span v-else-if="item.label == '审核状态'">
                        <span v-if="scope.row.auditStatus==1">待提交</span>
                        <span v-else-if="scope.row.auditStatus==2">审核中</span>
                        <span v-else-if="scope.row.auditStatus==3">通过</span>
                        <span v-else-if="scope.row.auditStatus==4">未通过</span>
                      </span>
                      <span v-else-if="item.label == '操作'">
                        <el-button v-if="scope.row.auditStatus==3&&(scope.row.supplierConfirm==0||scope.row.supplierConfirm==1)" size="mini" class="bottom_all_two" @click="userSubmit(scope.row)">
                          发送
                        </el-button>
                        <el-button v-if="scope.row.auditStatus==1" size="mini" class="bottom_all_two" @click="$router.push({ name: 'sign_material', query: { id: scope.row.statementNo, type: 1 } })">提交审核</el-button>
                      </span>
                      <span v-else-if="item.label == '供应商确认'">
                        <span v-if="scope.row.supplierConfirm==0">未发送</span>
                        <span v-else-if="scope.row.supplierConfirm==1">待查看</span>
                        <span v-else-if="scope.row.supplierConfirm==2">通过</span>
                        <!-- <span v-else-if="scope.row.supplierConfirm==3">拒绝</span> -->
                      </span>
                      <span v-else>{{ scope.row[item.prop] }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
            <!-- <div class="card_bottom">
              <div class="card_bottom_left">
                <div class="top_page_totle">总共{{ total }}条</div>
                <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" layout="prev, pager, next, jumper" :total="total" @current-change="currenindex==3?gettableData():pagesgettableData()"></el-pagination>
              </div>
              <div>
                <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="currenindex==3?gettableData():pagesgettableData()">刷新</el-button>
              </div>
            </div> -->
          </div>
        </div>
      </el-main>
      <div class="card_bottom">
        <div class="card_bottom_left">
          <div class="top_page_totle">总共{{ total }}条</div>
          <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" layout="prev, pager, next, jumper" :total="total" @current-change="currenindex==3?gettableData():pagesgettableData()"></el-pagination>
        </div>
        <div>
          <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="currenindex==3?gettableData():pagesgettableData()">刷新</el-button>
        </div>
      </div>
    </el-container>
    <!-- 选择供应商合同 -->
    <el-dialog v-dialogDrag :visible.sync="search" width="680px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">选择供应商合同</span>
      <div class="dialoginfo">
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="searchData" tooltip-effect="dark" @row-click='setradio'>
          <el-table-column align="center" label="选择">
            <template slot-scope="scope">
              <el-radio :value="searchradio" :label="JSON.stringify(scope.row)">{{''}}</el-radio>
            </template>
          </el-table-column>
          <el-table-column align="center" label="原物料合同编号" prop="contractNumber"></el-table-column>
          <el-table-column align="center" label="供应商单位" prop="supplierName"></el-table-column>
          <el-table-column align="center" label="是否包含运输">
            <template slot-scope="scope">
              {{scope.row.isCarriage==0?'否':'是'}}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="search=false">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px" @click="submitsearch">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 原物料-待结算-生成结算单 -->
    <el-dialog :visible.sync="billDeta" width="1180px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">原物料结算单</span>
      <div ref="html" style="padding:10px 20px">
        <div class="bill_top">
          <span><span class="text">供应商：</span>{{billDetails.supplier}}</span>
          <span><span class="text">结算时间段：</span>{{billDetails.startTime}}至{{billDetails.endTime}}</span>
          <span><span class="text">结算单编号：</span>{{billDetails.statementNo}}</span>
        </div>
        <div class="bill_title1">结算信息</div>
        <template v-for="(item,index) in billList">
          <div :key="index">
            <div class="bill_subtitle">
              <span><span class="text">协作单位：</span>{{item.cooperativeUnit}}</span>
              <span><span class="text">结算物料：</span>{{item.rawName}}</span>
            </div>
            <el-table :key="index" :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none'}" border stripe style="width: 100%" :data="item.list" tooltip-effect="dark">
              <el-table-column label="时间段" align="center" width="175">
                <template slot-scope="scope">
                  {{scope.row.startTime}}至{{scope.row.endTime}}
                </template>
              </el-table-column>
              <el-table-column label="站点" align="center" prop="receiveStation" width="120"></el-table-column>
              <el-table-column label="单价（元）" align="center" prop="unitPrice" width="120"></el-table-column>
              <el-table-column label="收货量" align="center" prop="receiveNum" width="120"></el-table-column>
              <el-table-column label="结算单价（元）" align="center" width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.statementUnitPrice" onchange="if(!value)value=0" placeholder="请输入" style="width:100%" onkeypress='return( /\d|\./.test(String.fromCharCode(event.keyCode)))' @input="scope.row.statementUnitPrice=$regExp.checkNum(scope.row.statementUnitPrice)" @blur="scope.row.statementUnitPrice=$regExp.blurCheckNum(scope.row.statementUnitPrice)"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="结算量（吨）" align="center" width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.statementNum" onchange="if(!value)value=0" placeholder="请输入" style="width:100%" onkeypress='return( /\d/.test(String.fromCharCode(event.keyCode)))'></el-input>
                </template>
              </el-table-column>
              <el-table-column label="应付金额（元）" align="center" prop="dealPrice" width="120">
                <template slot-scope="scope">
                  {{scope.row.dealPrice = (Math.round(((scope.row.statementUnitPrice||0) *(scope.row.statementNum||0)) * 100) / 100) }}
                </template>
              </el-table-column>
              <el-table-column label="增加金额（元）" align="center" width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.increaseAmount" onchange="if(!value)value=0" placeholder="请输入" style="width:100%" onkeypress='return( /\d|\./.test(String.fromCharCode(event.keyCode)))' @input="scope.row.increaseAmount=$regExp.checkNum(scope.row.increaseAmount)" @blur="scope.row.increaseAmount=$regExp.blurCheckNum(scope.row.increaseAmount)"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="结算金额（元）" align="center" width="120">
                <template slot-scope="scope">
                  {{(Math.round((Number(scope.row.dealPrice|| 0) + Number(scope.row.increaseAmount||0)) * 100) / 100) }}
                </template>
              </el-table-column>
              <el-table-column label="增加金额备注" align="center" width="220">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remark" placeholder="请输入" style="width:100%"></el-input>
                </template>
              </el-table-column>
            </el-table>
            <div style="border-top: 0px;" class="combined">小计：{{combined(item.list)}}</div>
          </div>
        </template>
        <!-- 结算补差 -->
        <div v-show="sendersList.length" class="bill_title">结算补差</div>
        <template v-for="(item,index) in sendersList">
          <div :key="index+'2'">
            <div class="bill_subtitle">
              <span><span class="text">协作单位：</span>{{item.cooperativeUnit}}</span>
            </div>
            <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="item.list" tooltip-effect="dark">
              <!-- <el-table-column label="开票单位" align="center" prop="cooperativeUnit"></el-table-column> -->
              <el-table-column label="物料名称" align="center" prop="rawName"></el-table-column>
              <el-table-column label="补差日期" align="center">
                <template slot-scope="scope">
                  {{scope.row.compensateStartTime+'-'+scope.row.compensateEndTime}}
                </template>
              </el-table-column>
              <el-table-column label="补差数量" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.compensateNum" placeholder="请输入" style="width:100%" onkeypress='return( /\d/.test(String.fromCharCode(event.keyCode)))'></el-input>
                </template>
              </el-table-column>
              <el-table-column label="补差单价（元）" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.compensatePrice" placeholder="请输入" style="width:100%" clearable onkeypress='return( /\d|\./.test(String.fromCharCode(event.keyCode)))'></el-input>
                </template>
              </el-table-column>
              <el-table-column label="补差金额（元）" align="center">
                <template slot-scope="scope">{{scope.row.compensateAmount=Number(scope.row.compensatePrice)*Number(scope.row.compensateNum)}}</template>
              </el-table-column>
            </el-table>
            <div style="border-top: 0px;" class="combined">小计：{{combined2(item,item.list)}}</div>
          </div>
        </template>
        <!-- 扣减金额 -->
        <div class="bill_title">扣减金额
          <el-button size="mini" class="bottom_all" style="margin-left: 24px" @click="addItem1()">
            <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
            添加
          </el-button>
        </div>
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="deductionList" tooltip-effect="dark">
          <el-table-column label="协作单位" align="center">
            <template slot-scope="scope">
              <el-select ref="select1" v-model="scope.row.cooperativeUnitId" filterable style="width:100%" placeholder="请选择协作单位" @change="$nextTick(()=>{scope.row.cooperativeUnit = $refs.select1.selectedLabel})">
                <el-option v-for="item in cooperativeUnitArr" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="站点" align="center">
            <template slot-scope="scope">
              <el-select ref="station1" v-model="scope.row.stationId" style="width:100%" placeholder="请选择站点" @change="$nextTick(()=>{scope.row.station = $refs.station1.selectedLabel})">
                <el-option v-for="item in stations" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="扣减类型" align="center">
            <template slot-scope="scope">
              <el-select ref="deductionType1" v-model="scope.row.deductionTypeId" style="width:100%" placeholder="请选择站点" @change="$nextTick(()=>{scope.row.deductionType = $refs.deductionType1.selectedLabel})">
                <el-option v-for="item in deductionTypes" :key="item.id" :label="item.itemName" :value="item.id"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="扣减金额" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.deduction" placeholder="请输入" style="width:100%" onkeypress='return( /\d|\./.test(String.fromCharCode(event.keyCode)))' @input="scope.row.deduction=$regExp.checkNum(scope.row.deduction)" @blur="scope.row.deduction=$regExp.blurCheckNum(scope.row.deduction)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="是否影响开票" align="center">
            <template slot-scope="scope">
              <el-radio-group v-model="scope.row.influenceInvoice">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入" style="width:100%" clearable></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="120">
            <template slot-scope="scope">
              <el-button size="mini" class="bottom_two" @click="delItem1(scope.$index)">
                <i class="icon iconfont iconicon_button_delete" style="font-size: 12px"></i>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 结算合计 -->
        <div class="bill_title">结算合计
          <el-button size="mini" class="bottom_all" style="margin-left: 24px" @click="addItem2()">
            <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
            添加
          </el-button>
        </div>
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="totalList" tooltip-effect="dark">
          <el-table-column label="开票单位" align="center">
            <template slot-scope="scope">
              <el-select v-if="scope.row.localstatus" ref="cooperativeUnit2" v-model="scope.row.cooperativeUnitId" filterable style="width:100%" placeholder="请选择" @change="$nextTick(()=>{scope.row.cooperativeUnit = $refs.cooperativeUnit2.selectedLabel}),check1('结算合计',scope.$index)">
                <el-option v-for="item in cooperativeUnit" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
              <div v-else>{{scope.row.cooperativeUnit}}</div>
            </template>
          </el-table-column>
          <el-table-column label="结算金额（元）" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.localstatus?'---':scope.row.settlementAmount}}</div>
            </template>
          </el-table-column>
          <el-table-column label="补差金额（元）" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.localstatus?'---':scope.row.compensateAmount}}</div>
            </template>
          </el-table-column>
          <el-table-column label="扣减金额（元）" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.localstatus?'---':scope.row.deduction}}</div>
            </template>
          </el-table-column>
          <el-table-column label="实付金额（元）" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.localstatus?'---':scope.row.realPay}}</div>
            </template>
          </el-table-column>
          <el-table-column label="票面调整（元）" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.faceAdjustment" placeholder="请输入" style="width:100%" onkeypress='return( /\d|\./.test(String.fromCharCode(event.keyCode)))' @input="scope.row.faceAdjustment=$regExp.checkNum(scope.row.faceAdjustment)" @blur="scope.row.faceAdjustment=$regExp.blurCheckNum(scope.row.faceAdjustment)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="120">
            <template slot-scope="scope">
              <el-button v-if="scope.row.localstatus" size="mini" class="bottom_two" @click="delItem2(scope.$index)">
                <i class="icon iconfont iconicon_button_delete" style="font-size: 12px"></i>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer" style="display:flex;justify-content: space-between;">
        <div>
          <el-button class="bottom_all_two" @click="combinedSubmit(1)">提交审核</el-button>
        </div>
        <div>
          <el-button class="bottom_all_two" @click="billDeta=false">关 闭</el-button>
          <el-button class="bottom_all" style="margin-left: 24px" @click="combinedSubmit(0)">保 存</el-button>
        </div>
      </span>
    </el-dialog>
    <!-- 原物料-结算单-编号-查看或修改 -->
    <el-dialog :visible.sync="billDeta1" width="1180px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">原物料结算单</span>
      <div ref="html" style="padding:10px 20px">
        <div class="bill_top">
          <span><span class="text">供应商：</span>{{billDetails1.supplier}}</span>
          <span><span class="text">结算时间段：</span>{{billDetails1.startTime}}至{{billDetails1.endTime}}</span>
          <span><span class="text">结算单编号：</span>{{billDetails1.statementNo}}</span>
        </div>
        <div class="bill_title1" style="padding-bottom: 15px;">结算信息</div>
        <template v-for="(item,index) in billList">
          <div :key="index">
            <div class="bill_subtitle">
              <span><span class="text">协作单位：</span>{{item.cooperativeUnit}}</span>
              <span><span class="text">结算物料：</span>{{item.rawName}}</span>
            </div>
            <el-table :key="index" :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none'}" border stripe style="width: 100%" :data="item.list" tooltip-effect="dark">
              <el-table-column label="时间段" align="center" width="175">
                <template slot-scope="scope">
                  {{scope.row.startTime}}至{{scope.row.endTime}}
                </template>
              </el-table-column>
              <el-table-column label="站点" align="center" prop="receiveStation" width="120"></el-table-column>
              <el-table-column label="单价（元）" align="center" prop="unitPrice" width="120"></el-table-column>
              <el-table-column label="收货量" align="center" prop="receiveNum" width="120"></el-table-column>
              <el-table-column label="结算单价（元）" align="center" width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.statementUnitPrice" :disabled="low.auditStatus!=1" placeholder="请输入" style="width:100%" oninput="if(value > 999999999999 ){value = 999999999999}" onkeypress='return( /\d|\./.test(String.fromCharCode(event.keyCode)))' @input="scope.row.statementUnitPrice=$regExp.checkNum(scope.row.statementUnitPrice)" @blur="scope.row.statementUnitPrice=$regExp.blurCheckNum(scope.row.statementUnitPrice)"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="结算量（吨）" align="center" width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.statementNum" :disabled="low.auditStatus!=1" placeholder="请输入" style="width:100%" onkeypress='return( /\d/.test(String.fromCharCode(event.keyCode)))'></el-input>
                </template>
              </el-table-column>
              <el-table-column label="应付金额（元）" align="center" prop="dealPrice" width="120">
                <template slot-scope="scope">
                  {{scope.row.dealPrice = (Math.round((scope.row.statementUnitPrice *scope.row.statementNum) * 100) / 100) }}
                </template>
              </el-table-column>
              <el-table-column label="增加金额（元）" align="center" width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.increaseAmount" :disabled="low.auditStatus!=1" placeholder="请输入" style="width:100%" onkeypress='return( /\d|\./.test(String.fromCharCode(event.keyCode)))' @input="scope.row.increaseAmount=$regExp.checkNum(scope.row.increaseAmount)" @blur="scope.row.increaseAmount=$regExp.blurCheckNum(scope.row.increaseAmount)"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="结算金额（元）" align="center" width="120">
                <template slot-scope="scope">
                  {{scope.row.realPay =(Math.round(( Number(scope.row.dealPrice) + Number(scope.row.increaseAmount)) * 100) / 100) }}
                </template>
              </el-table-column>
              <el-table-column label="增加金额备注" align="center" width="220">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remark" :disabled="low.auditStatus!=1" placeholder="请输入" style="width:100%"></el-input>
                </template>
              </el-table-column>
            </el-table>
            <div style="border-top: 0px;" class="combined">小计：{{combined(item.list)}}</div>
          </div>
        </template>
        <!-- 结算补差 -->
        <div v-show="sendersList.length" class="bill_title">结算补差</div>
        <template v-for="(item,index) in sendersList">
          <div :key="index+'2'">
            <div class="bill_subtitle">
              <span><span class="text">协作单位：</span>{{item.cooperativeUnit}}</span>
            </div>
            <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="item.list" tooltip-effect="dark">
              <!-- <el-table-column label="开票单位" align="center" prop="cooperativeUnit"></el-table-column> -->
              <el-table-column label="物料名称" align="center" prop="rawName"></el-table-column>
              <el-table-column label="补差日期" align="center">
                <template slot-scope="scope">
                  {{scope.row.compensateStartTime+'-'+scope.row.compensateEndTime}}
                </template>
              </el-table-column>
              <el-table-column label="补差数量" align="center" prop="compensateNum">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.compensateNum" :disabled="low.auditStatus!=1" style="width:100%" type="Number" onkeypress='return( /\d/.test(String.fromCharCode(event.keyCode)))'></el-input>
                </template>
              </el-table-column>
              <el-table-column label="补差单价（元）" align="center" prop="compensatePrice">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.compensatePrice" :disabled="low.auditStatus!=1" style="width:100%" clearable onkeypress='return( /\d|\./.test(String.fromCharCode(event.keyCode)))' @input="scope.row.compensatePrice=$regExp.checkNum(scope.row.compensatePrice)" @blur="scope.row.compensatePrice=$regExp.blurCheckNum(scope.row.compensatePrice)"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="补差金额（元）" align="center" prop="compensateAmount">
                <template slot-scope="scope">{{scope.row.compensateAmount=Number(scope.row.compensatePrice)*Number(scope.row.compensateNum)}}</template>
              </el-table-column>
            </el-table>
            <div style="border-top: 0px;" class="combined">小计：{{combined2(item,item.list)}}</div>
          </div>
        </template>
        <!-- 扣减金额 -->
        <div class="bill_title">扣减金额
          <el-button v-show="low.auditStatus==1" size="mini" class="bottom_all" style="margin-left: 24px" @click="addItem1()">
            <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
            添加
          </el-button>
        </div>
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="deductionList" tooltip-effect="dark">
          <el-table-column label="协作单位" align="center" prop="cooperativeUnit">
            <template slot-scope="scope">
              <el-select ref="select2" v-model="scope.row.cooperativeUnitId" :disabled="low.auditStatus!=1" filterable style="width:100%" placeholder="请选择协作单位" @change="$nextTick(()=>{scope.row.cooperativeUnit = $refs.select2.selectedLabel})">
                <el-option v-for="item in cooperativeUnitArr" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="站点" align="center" prop="station">
            <template slot-scope="scope">
              <el-select ref="station1" v-model="scope.row.stationId" :disabled="low.auditStatus!=1" style="width:100%" placeholder="请选择站点" @change="$nextTick(()=>{scope.row.station = $refs.station1.selectedLabel})">
                <el-option v-for="item in stations" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="扣减类型" align="center" prop="deductionType">
            <template slot-scope="scope">
              <el-select ref="deductionType1" v-model="scope.row.deductionTypeId" style="width:100%" placeholder="请选择站点" :disabled="low.auditStatus!=1" @change="$nextTick(()=>{scope.row.deductionType = $refs.deductionType1.selectedLabel})">
                <el-option v-for="item in deductionTypes" :key="item.id" :label="item.itemName" :value="item.id"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="扣减金额" align="center" prop="deduction">
            <template slot-scope="scope">
              <el-input v-model="scope.row.deduction" :disabled="low.auditStatus!=1" placeholder="请输入" style="width:100%" onkeypress='return( /\d|\./.test(String.fromCharCode(event.keyCode)))' @input="scope.row.deduction=$regExp.checkNum(scope.row.deduction)" @blur="scope.row.deduction=$regExp.blurCheckNum(scope.row.deduction)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="是否影响开票" align="center">
            <template slot-scope="scope">
              <el-radio-group v-model="scope.row.influenceInvoice" :disabled="low.auditStatus!=1">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" :disabled="low.auditStatus!=1" placeholder="请输入" style="width:100%" clearable></el-input>
            </template>
          </el-table-column>
          <el-table-column v-if="low.auditStatus==1" label="操作" align="left" width="120">
            <template slot-scope="scope">
              <el-button size="mini" class="bottom_two" @click="delItem1(scope.$index)">
                <i class="icon iconfont iconicon_button_delete" style="font-size: 12px"></i>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 结算合计 -->
        <div class="bill_title">结算合计
          <el-button v-if="low.auditStatus==1" size="mini" class="bottom_all" style="margin-left: 24px" @click="addItem2()">
            <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
            添加
          </el-button>
        </div>
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="totalList" tooltip-effect="dark">
          <el-table-column label="开票单位" align="center" prop="cooperativeUnit">
            <template slot-scope="scope">
              <el-select v-if="scope.row.localstatus" ref="cooperativeUnit2" v-model="scope.row.cooperativeUnitId" :disabled="low.auditStatus!=1" filterable style="width:100%" placeholder="请选择" @change="$nextTick(()=>{scope.row.cooperativeUnit = $refs.cooperativeUnit2.selectedLabel}),check3('结算合计',scope.$index)">
                <el-option v-for="item in cooperativeUnit" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
              <div v-else>{{scope.row.cooperativeUnit}}</div>
            </template>
          </el-table-column>
          <el-table-column label="结算金额（元）" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.settlementAmount||scope.row.settlementAmount==0?scope.row.settlementAmount:'---'}}</div>
            </template>
          </el-table-column>
          <el-table-column label="补差金额（元）" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.compensateAmount||scope.row.compensateAmount==0?scope.row.compensateAmount:'---'}}</div>
            </template>
          </el-table-column>
          <el-table-column label="扣减金额（元）" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.deduction||scope.row.deduction==0?scope.row.deduction:'---'}}</div>
            </template>
          </el-table-column>
          <el-table-column label="实付金额（元）" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.realPay||scope.row.realPay==0?scope.row.realPay:'---'}}</div>
            </template>
          </el-table-column>
          <el-table-column label="票面调整（元）" align="center" prop="faceAdjustment">
            <template slot-scope="scope">
              <el-input v-model="scope.row.faceAdjustment" :disabled="low.auditStatus!=1" placeholder="请输入" style="width:100%" onkeypress='return( /\d|\./.test(String.fromCharCode(event.keyCode)))' @input="scope.row.faceAdjustment=$regExp.checkNum(scope.row.faceAdjustment)" @blur="scope.row.faceAdjustment=$regExp.blurCheckNum(scope.row.faceAdjustment)"></el-input>
            </template>
          </el-table-column>
          <el-table-column v-if="low.auditStatus==1" label="操作" align="left" width="120">
            <template slot-scope="scope">
              <el-button size="mini" class="bottom_two" @click="delItem2(scope.$index)">
                <i class="icon iconfont iconicon_button_delete" style="font-size: 12px"></i>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer" style="display:flex;justify-content: space-between;">
        <div>
          <el-button class="bottom_all_two" @click="downloadLink">下载结算单</el-button>
          <!-- <el-button v-if="billDetails1.auditStatus==1" class="bottom_all_two" @click="combinedSubmit(3)">提交审核</el-button> -->
          <el-button class="bottom_all_two" @click="daYinTypeFun()">打印结算单</el-button>
        </div>
        <div>
          <el-button class="bottom_all_two" @click="billDeta1=false">关 闭</el-button>
          <el-button v-if="low.auditStatus==1" class="bottom_all" style="margin-left: 24px" @click="combinedSubmit_3()">保 存</el-button>
        </div>
      </span>
    </el-dialog>
    <!--选择发送的人员-->
    <!-- <el-dialog v-dialogDrag :visible.sync="userDeta" width="620px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">请选择接收账号</span>
      <div style="padding:0 10px">
        <el-checkbox-group v-model="userarr">
          <template v-for="(item,index) in useroptons">
            <el-checkbox :key="index" style="line-height:26px" :label="item.id">{{item.name}}</el-checkbox>
          </template>
        </el-checkbox-group>
        <div v-if="useroptons.length==0" style="color:#ccc;text-align: center;">无数据</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="userDeta=false">取 消</el-button>
        <el-button class="bottom_all" :disabled="userarr.length==0" style="margin-left: 24px" @click="userSubmit()">发 送</el-button>
      </span>
    </el-dialog> -->
    <!--打印结算单-->
    <el-dialog v-dialogDrag :visible.sync="daYinType" width="1130px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">打印结算单预览</span>
      <div style="padding:0 10px">
        <div id="dyBox">
          <div>
            <div class="top">
              <div>采购结算书</div>
              <div>
                <div>合同（协议）编号： <span>{{daYinForm.contractNo}}</span></div>
                <div>结算周期： <span>{{daYinForm.startTime}}至{{daYinForm.endTime}}</span></div>
              </div>
            </div>
            <div class="formBox">
              <div>
                <div>
                  <span class="table">采购类别<span></span></span>
                  <span>{{daYinForm.rawType}}</span>
                </div>
                <div>
                  <span class="table">结算数量<span></span></span>
                  <span>{{daYinForm.statementNum}}</span>
                </div>
              </div>
              <div>
                <div style="position: relative;" @mouseenter="receivingUnitType = true" @mouseleave="receivingUnitType = false">
                  <span class="table">收货单位<span></span></span>
                  <span>{{daYinForm.receivingUnit}}</span>
                  <el-select v-show="receivingUnitType" v-model="daYinForm.receivingUnit" placeholder="请选择" style="width:319px;position: absolute;top:-11px;left:115px;">
                    <el-option v-for="(item,k) in ReceivingUnitList" :key="k" :label="item.itemName" :value="item.itemName">
                    </el-option>
                  </el-select>
                </div>
                <div>
                  <span class="table">结算金额<span></span></span>
                  <span>{{daYinForm.realPay}}</span>
                </div>
              </div>
              <div>
                <div>
                  <span class="table">招采部负责人<span></span></span>
                  <span></span>
                </div>
                <div>
                  <span class="table">金额大写<span></span></span>
                  <span>{{daYinForm.realPay0}}</span>
                </div>
              </div>
              <div>
                <div>
                  <span class="table">招采部审核人<span></span></span>
                  <span></span>
                </div>
                <div>
                </div>
              </div>
              <div>
                <div>
                  <span class="table">砼事业部负责人<span></span></span>
                  <span></span>
                </div>
                <div>
                  <span class="table">供货单位经办人<span></span></span>
                  <span></span>
                </div>
              </div>
              <div>
                <div>
                  <span class="table">砼事业部审核人<span></span></span>
                  <span></span>
                </div>
                <div>
                </div>
              </div>
              <div>
                <div>
                  <span class="table">经办人<span></span></span>
                  <span></span>
                </div>
                <div>
                  <span class="table">供货单位（章）<span></span></span>
                  <span>{{daYinForm.supplier}}</span>
                </div>
              </div>
            </div>
            <div class="tableBox">
              <div>采购结算明细表</div>
              <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none'}" border stripe style="width: 100%" :data="daYinForm.list" tooltip-effect="dark">
                <el-table-column prop="receiveStation" label="站点">
                </el-table-column>
                <el-table-column prop="rawName" label="材料名称">
                </el-table-column>
                <el-table-column prop="specification" label="规格">
                </el-table-column>
                <el-table-column label="计量单位">
                  <template>
                    <div>
                      吨
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="statementNum" label="数量">
                </el-table-column>
                <el-table-column prop="unitPrice" label="合同单价">
                </el-table-column>
                <el-table-column prop="" label="调整单价">
                  <template slot-scope="scope">
                    {{Number(scope.row.statementUnitPrice)- Number(scope.row.unitPrice) }}
                  </template>
                </el-table-column>
                <el-table-column prop="statementUnitPrice" label="结算单价">
                </el-table-column>
                <el-table-column prop="" label="结算金额(元)">
                  <template slot-scope="scope">
                    {{scope.row.realPay = Number(scope.row.dealPrice) + Number(scope.row.increaseAmount) }}
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注">
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="daYinType = false">关 闭</el-button>
        <el-button class="bottom_all" style="margin-left: 24px;" @click="doPrint()">打 印</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mixin from "@/mixins/ICPSmixin.js";
import {
  queryPage1, queryPage2, queryPage3, get_contract_list, get_raw_list, get_query_condition, generate_statement_detail, get_supplier,
  generate_statement_compensate, save_statement_detail, get_statement_detail, update_supplier_confirm, Download, update_statement_detail
} from "@/api/wise/material.js";
import { _debounce } from '@/utils/utils.js'
import html2canvas from 'html2canvas';
import { getUserInfo } from "@/utils/auth.js";
import { getcompany, getUserAutList } from "@/api/common.js";
import { cooperationqueryListsByPid } from "@/api/GHnumber/contract.js";
import {
  queryUserByID,
  informClient
} from "@/api/wise/Wise_contactsbusiness/Wise_contactsbusiness.js";
import { getDicType } from "@/api/common.js";
export default {
  mixins: [mixin],
  data() {
    return {
      receivingUnitType: false,
      ReceivingUnitList: [],
      typelist: [],
      daYinForm: { list: [], receivingUnit: '请选择' },
      daYinType: false,
      companyId: '',
      company: '',
      companylist: [],
      stationId: '',
      stationName: '',
      stationIdlist: [],
      /*表格增删改查及下载接口*/
      queryPage: '',
      download: Download,
      /*表格数据*/
      table: [],
      table1: [
        { label: "供应商", width: "auto", prop: "supplier", status: true },
        { label: "协作单位", width: "120", prop: "cooperativeUnit", status: true },
        { label: "物料名称", width: "auto", prop: "rawName", status: true },
        { label: "运输车辆", width: "120", prop: "deliveryVehicl", status: true },
        { label: "货票量", width: "auto", prop: "ticketNum", status: true },
        { label: "收货量", width: "120", prop: "receiveNum", status: true },
        { label: "收货时间", width: "auto", prop: "actualReceiveTime", status: true },
        { label: "收货站点", width: "120", prop: "receiveStation", status: true },
      ],
      table2: [
        { label: "结算单编号", width: "200", prop: "statementNo", status: true },
        { label: "供应商", width: "160", prop: "supplier", status: true },
        { label: "结算时间段", width: "310", prop: "", status: true },
        { label: "结算总金额（元）", width: "140", prop: "statementAmount", status: true },
        { label: "提交时间", width: "160", prop: "submitTime", status: true },
        { label: "审核状态", width: "120", prop: "", status: true },
        { label: "操作", width: "120", prop: "", status: true },
        { label: "供应商确认", width: "120", prop: "", status: true },
      ],
      pagesType: 0,
      /**导航栏*/
      navlist: [
        {
          value: "待结算",
          id: 1,
        },
        {
          value: "已结算",
          id: 2,
        },
        {
          value: "结算单",
          id: 3,
        },
      ],
      currenindex: 1,
      datePicker: [],
      searchText: '',
      search: false,
      searchData: [],
      searchradio: '',
      cooperativeUnit: [],
      stations: [],
      rawId: [],
      contractId: [],
      generate: {
        logisticsList: [],
        clearingSourceId: '',
        startTime: '',
        endTime: '',
        contractId: ''
      },
      deductionTypes: [],
      /*结算单*/
      billDeta: false,
      billDetails: {},
      billList: [],
      sendersList: [],
      deductionList: [],
      deductionListCopy: [],
      totalList: [],
      totalListCopy: [],
      /**查看阶段单*/
      billDeta1: false,
      UserInfo: {},
      billDetails1: { list: [] },
      userDeta: false,
      useroptons: [],
      userarr: [],
      low: {},
      cooperativeUnitArr: []//扣减金额-协作单位
    };
  },
  async created() {
    const { data } = await getDicType({ code: 'deductionType' })
    this.deductionTypes = data.items
    /*存储拷贝的原初始化fromDate数据*/
    this.tableParam = { ...this.tableParam, startTime: "", endTime: "", contractId: '', cooperativeUnitList: [], receiveStationIdList: [], rawIdList: '' };
    this.UserInfo = getUserInfo();
    if (this.UserInfo.adminStatus == 1) {
      /**通过typeId为公司类型id查询所有公司 */
      getcompany({ typeId: "19da56b9e85648059e3cf1e7da497da4" }).then((res) => {
        this.companylist = res.data;
      });
    } else {
      this.stationIdlist = await getUserAutList(true)
    }
    getDicType({ code: "MATtype" }).then((res) => {
      this.typelist = res.data.items;
    });
    getDicType({ code: "ReceivingUnitType" }).then((res) => {
      this.ReceivingUnitList = res.data.items;
    });
  },
  watch: {
    currenindex: {
      handler() {
        this.tableData = []
        this.datePicker = []
        this.init()

        if (this.currenindex == 1) {
          this.searchText = ''
          this.table = this.table1;
          this.queryPage = queryPage2

        }
        if (this.currenindex == 2) {
          this.table = this.table1;
          this.queryPage = queryPage1
          this.getsearchData()
        }
        if (this.currenindex == 3) {
          this.table = this.table2;
          this.queryPage = queryPage3
          this.getsearchData()
          this.gettableData()
        }
        //此处为执行的函数或者方法
      },
      deep: false, //是否深度监听，true为是，默认为false
      immediate: true, //immediate表示在watch中首次绑定的时候，是否执行handler,true为执行,默认为false
    },
    datePicker() {
      if (this.datePicker) {
        this.tableParam.startTime = this.datePicker[0]
        this.tableParam.endTime = this.datePicker[1]
      } else {
        this.tableParam.startTime = ''
        this.tableParam.endTime = ''
      }
    },
    tableData() {
      if (this.tableData.length !== 0) {
        this.$refs.table.toggleAllSelection()
        this.generate.startTime = this.tableParam.startTime
        this.generate.endTime = this.tableParam.endTime
        this.generate.contractId = this.tableParam.contractId
      }
    },
    /**结算合计*/
    tatol: {
      handler() {
        this.settotalList()
      },
      deep: true,
      immediate: false,
    },
  },
  computed: {
    tatol() {
      return {
        billList: this.billList,
        sendersList: this.sendersList,
        deductionList: this.deductionList
      }
    }
  },
  methods: {
    /**扣减金额*/
    addItem1() {
      let obj = {
        cooperativeUnitId: '',
        cooperativeUnit: '',
        stationId: '',
        station: '',
        deductionTypeId: '',
        deductionType: '',
        deduction: '',
        influenceInvoice: 0,
        remark: ''
      }
      this.deductionList.push(obj)
    },
    delItem1(index) {
      this.deductionList.splice(index, 1)
    },
    /**结算合计*/
    addItem2() {
      let obj = {
        compensateAmount: '',
        cooperativeUnit: '',
        cooperativeUnitId: '',
        faceAdjustment: '',
        realPay: '',
        settlementAmount: '',
        statementNo: '',
        deduction: '',
        localstatus: true
      }
      this.totalList.push(obj)
    },
    delItem2(index) {
      this.totalList.splice(index, 1)
    },
    downloadLink() {
      this.$Download(this.download, { statementNo: this.low.statementNo })
    },
    /**结算信息合计*/
    combined(arr) {
      let num = 0
      arr.forEach(res => {
        num = Number(res.dealPrice) + Number(res.increaseAmount) + num
      })
      return num.toFixed(2)
    },
    /**结算补差合计*/
    combined2(item, arr) {
      let num = 0
      arr.forEach(res => {
        num = (Number(res.compensateNum) * Number(res.compensatePrice)) + num
      })
      item['compensateAmount'] = num
      return num.toFixed(2)
    },
    /**结算合计*/
    settotalList: _debounce(function () {
      let _this = this
      let list = []
      let totalList = []
      let newtotalList = []
      _this.billList.forEach(res => {
        list = list.concat(res.list)
      })
      let newsendersList = []
      _this.sendersList.forEach(res => {
        let index = newsendersList.findIndex(item => (item.cooperativeUnitId == res.cooperativeUnitId))
        if (index == -1) {
          newsendersList.push({ cooperativeUnitId: res.cooperativeUnitId, compensateAmount: res.compensateAmount })
        } else {
          newsendersList[index].realPay = Number(res.compensateAmount) + Number(newsendersList[index].compensateAmount)
        }
      })
      list.forEach(res => {
        let index = newtotalList.findIndex(item => (item.cooperativeUnitId == res.cooperativeUnitId))
        if (index == -1) {
          newtotalList.push({ cooperativeUnitId: res.cooperativeUnitId, cooperativeUnit: res.cooperativeUnit, settlementAmount: (Math.round((Number(res.dealPrice) + Number(res.increaseAmount)) * 100) / 100), compensateAmount: null, realPay: (Math.round((Number(res.dealPrice) + Number(res.increaseAmount)) * 100) / 100), faceAdjustment: (Math.round((Number(res.dealPrice) + Number(res.increaseAmount)) * 100) / 100), statementNo: res.statementNo, })
        } else {
          newtotalList[index].settlementAmount = (Math.round((Number(newtotalList[index].settlementAmount) + Number(res.dealPrice)) * 100) / 100)
          newtotalList[index].realPay = (Math.round((Number(newtotalList[index].realPay) + Number(res.dealPrice) + Number(res.increaseAmount)) * 100) / 100)
          newtotalList[index].faceAdjustment = (Math.round((Number(newtotalList[index].faceAdjustment) + Number(res.dealPrice) + Number(res.increaseAmount)) * 100) / 100)
        }
      })
      totalList = newtotalList.map(res => {
        let item1 = newsendersList.find(item => (item.cooperativeUnitId == res.cooperativeUnitId))
        console.log(item1);
        let item2 = this.deductionList.filter(item => (item.cooperativeUnitId == res.cooperativeUnitId))
        const sum = (prev, cur) => (prev + Number(cur.deduction))
        let deduction = item2.reduce(sum, 0)
        console.log(deduction)
        let obj = new Object()
        obj.compensateAmount = 0
        if (item1) {
          obj.compensateAmount = item1.compensateAmount
        }
        obj.cooperativeUnit = res.cooperativeUnit
        obj.cooperativeUnitId = res.cooperativeUnitId
        obj.faceAdjustment = res.faceAdjustment + obj.compensateAmount - (deduction || 0)
        console.log(res.settlementAmount, obj.compensateAmount, deduction);
        obj.realPay = res.settlementAmount + obj.compensateAmount - (deduction || 0)
        console.log(obj.realPay);
        obj.settlementAmount = res.settlementAmount
        console.log(obj.settlementAmount);
        obj.deduction = deduction || 0
        obj.statementNo = null
        return obj
      })
      let totalList1 = _this.totalList.filter(res => (res.localstatus))
      _this.totalList = [...totalList, ...totalList1]
      console.log(_this.totalList);
    }, 500),
    /**表格选中*/
    pageshandleSelectionChange(val) {
      this.generate.logisticsList = val.map(res => {
        let obj = new Object()
        obj.cooperativeUnit = res.cooperativeUnit
        obj.cooperativeUnitId = res.cooperativeUnitId
        obj.rawId = res.rawId
        obj.rawName = res.rawName
        obj.receiveStation = res.receiveStation
        obj.receiveStationId = res.receiveStationId
        obj.receiveNum = res.receiveNum
        obj.actualReceiveTime = res.actualReceiveTime
        obj.consignmentId = res.id
        obj.carNo = res.deliveryVehicl
        obj.ticketNum = res.ticketNum
        obj.unitPrice = res.price
        obj.specification = res.specification
        return obj
      })
    },
    /**生成结算单h和补差价*/
    async statements() {
      let _this = this
      await generate_statement_detail(this.generate).then(res => {
        _this.billDetails = res.data;
        console.log(this.billDetails.cooperativeUnit);
        _this.billList = [];
        this.cooperativeUnitArr = []
        const stationName = []
        //结算信息--开始
        res.data.list.forEach(res => {
          stationName.push(res.receiveStation);
          let index = _this.billList.findIndex(item => (item.cooperativeUnitId == res.cooperativeUnitId && item.rawId == res.rawId))
          if (index == -1) {
            let arr = []
            arr.push(res)
            _this.billList.push({ cooperativeUnit: res.cooperativeUnit, cooperativeUnitId: res.cooperativeUnitId, rawName: res.rawName, rawId: res.rawId, list: arr })
          } else {
            _this.billList[index].list.push(res)
          }
        })
        //结算信息--完成
        console.log(JSON.parse(JSON.stringify(this.billList)))
        this.cooperativeUnitArr = this.billList.map((res) => {
          return {
            name: res.cooperativeUnit,
            id: res.cooperativeUnitId
          }
        })
        console.log(JSON.parse(JSON.stringify(this.cooperativeUnitArr)))
        this.stationName = Array.from(new Set(stationName)).join(',');
      })
      let data = {
        logisticsList: this.generate.logisticsList,
        contractId: this.tableParam.contractId,
        clearingSourceId: this.generate.clearingSourceId
      }
      _this.sendersList = []
      await generate_statement_compensate(data).then(res2 => {
        if (res2.data) {
          let list2 = res2.data
          list2.forEach((val) => {
            let index = this.sendersList.findIndex(item => (item.cooperativeUnitId == val.cooperativeUnit))
            if (index == -1) {
              let arr = []
              arr.push(val)
              this.sendersList.push({ cooperativeUnit: val.cooperativeUnit, cooperativeUnitId: val.cooperativeUnitId, list: arr })
            } else {
              this.sendersList[index].list.push(val)
            }
          })
        }
      })
      _this.billDeta = true

    },
    /**结算单发给供应商*/
    send(low) {
      this.low = low
      this.userarr = []
      this.useroptons = []
      queryUserByID({ id: low.contractId }).then(res => {
        this.useroptons = res.data
        this.userDeta = true
      })
    },
    async userSubmit(low) {
      this.$confirm('确认发送?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'bottom_all_two',
        confirmButtonClass: 'bottom_all',
        type: 'warning'
      }).then(async () => {
        let json = {
          contractId: low.contractId,
          type: 2,
          settlementId: low.id,
          settlementNo: low.statementNo,
          times: low.startTime + '-' + low.endTime,
          money: low.statementAmount,
          applyForTime: low.submitTime,
          imgUrl: low.picture,
        }
        // let arr = this.userarr.map(res => (new useritem(res)))
        await informClient(json).then(res => {
          if (res.code == 1001) {
            update_supplier_confirm({ statementNo: low.statementNo, supplierConfirm: 1 }).then(() => { })
            this.$message({
              message: '发送成功',
              type: 'success'
            });
            this.gettableData()
            this.userDeta = false
          }
        })
      })
    },
    /**保存结算单*/
    async combinedSubmit(num) {
      let _this = this
      // if (num == 3) {
      //   _this.$router.push({ name: "sign_material", query: { id: _this.low.statementNo, type: 1 } });
      //   return
      // }
      let data = new Object()
      await html2canvas(_this.$refs.html).then((res) => {
        let url = res.toDataURL('image/png');
        data.picture = url
      })
      let list = []
      let total = 0
      let total2 = 0
      _this.billList.forEach(res => {
        list = list.concat(res.list)
      })
      console.log(_this.totalList)
      _this.totalList.forEach(res => {
        total = total + Number(res.realPay)
        total2 = total2 + Number(res.faceAdjustment)
      })
      if (total !== total2) {
        _this.$message({
          message: '票面调整之和要等于实付金额之和',
          type: 'warning'
        });
        return
      }
      data.list = list
      let sendersListArr = []
      _this.sendersList.forEach(res => {
        sendersListArr = sendersListArr.concat(res.list)
      })
      data.compensateList = sendersListArr
      data.logisticsList = _this.billDetails.logisticsList
      data.clearingSourceId = _this.generate.clearingSourceId
      data.statementNo = _this.billDetails.statementNo
      data.supplier = JSON.parse(_this.searchradio).supplierName
      data.supplierId = JSON.parse(_this.searchradio).supplierId
      data.startTime = _this.tableParam.startTime
      data.endTime = _this.tableParam.endTime
      data.statementAmount = total// 结算合计，合计
      data.operation = 0	//0：保存，1：提交审核
      data.submitTime = new Date().Format('yyyy-MM-dd hh:mm:ss')		// 提交审核时间
      data.contractId = _this.tableParam.contractId
      data.contractNo = _this.tableParam.contractNo
      data.rawTypeId = _this.tableParam.rawTypeId
      data.rawType = _this.tableParam.rawType
      data.deductionList = _this.deductionList
      data.company = _this.company
      data.companyId = _this.companyId
      data.totalList = _this.totalList
      // data.stationId = _this.stationId
      console.log(data)
      save_statement_detail(data).then(res => {
        if (res.code == 1001) {
          _this.billDeta = false
          if (num == 1) {
            _this.$router.push({ name: "sign_material", query: { id: res.data, type: 1 } });
            return
          }
          _this.$message({
            message: '保存成功',
            type: 'success'
          });
          _this.gettableData()
        }
      })
    },
    /**修改结算单 */
    async combinedSubmit_3() {
      let _this = this
      let data = new Object()
      await html2canvas(_this.$refs.html).then((res) => {
        let url = res.toDataURL('image/png');
        // console.log(url)
        data.picture = url
      })
      let list = []
      let total = 0
      let total2 = 0
      _this.billList.forEach(res => {
        list = list.concat(res.list)
      })
      console.log(_this.totalList)
      _this.totalList.forEach(res => {
        total = total + Number(res.realPay)
        total2 = total2 + Number(res.faceAdjustment)
      })
      if (total !== total2) {
        _this.$message({
          message: '票面调整之和要等于实付金额之和',
          type: 'warning'
        });
        return
      }
      let form = {}
      form = this.billDetails1
      form.list = list
      let compensateList = []
      this.sendersList.forEach(res => {
        compensateList = compensateList.concat(res.list)
      })
      form.compensateList = compensateList
      //扣减金额 数据处理开始
      let deductionList = []
      let update = this.deductionList.filter((res) =>
        this.deductionListCopy.some((item) => res.id == item.id)
      );
      let deleteData = this.deductionListCopy.filter(
        (res) => !update.some((item) => res.id == item.id)
      );
      deleteData.forEach((res) => {
        res.status = 0; //0是删除
      });
      let addData = this.deductionList.filter(
        //新增的type默认写死为 1
        (res) => !update.some((item) => res.id == item.id)
      );
      deductionList = [...update, ...deleteData, ...addData];
      form.deductionList = deductionList
      //扣减金额 数据处理结束
      form.totalList = this.totalList
      form.operation = 0
      form.statementAmount = total// 结算合计，合计
      update_statement_detail(form).then(res => {
        if (res.code == 1001) {
          _this.billDeta1 = false
          _this.$message({
            message: '保存成功',
            type: 'success'
          });
          _this.gettableData()
        }
      })
    },
    show(low) {
      this.low = low
      get_statement_detail({ statementNo: low.statementNo }).then(res => {
        if (res.code == 1001) {
          cooperationqueryListsByPid({ supplierId: res.data.supplierId }).then((res) => {
            this.cooperativeUnit = res.data
          })
          this.billDetails1 = res.data;
          this.daYinForm = res.data;
          this.deductionList = res.data.deductionList
          this.deductionListCopy = JSON.parse(JSON.stringify(res.data.deductionList))
          this.stations = JSON.parse(res.data.stations)
          this.billDeta1 = true

          this.billList = [];
          this.cooperativeUnitArr = []
          res.data.list.forEach(res => {
            let index = this.billList.findIndex(item => (item.cooperativeUnitId == res.cooperativeUnitId && item.rawId == res.rawId))
            if (index == -1) {
              let arr = []
              arr.push(res)
              this.billList.push({ cooperativeUnit: res.cooperativeUnit, cooperativeUnitId: res.cooperativeUnitId, rawName: res.rawName, rawId: res.rawId, list: arr })
            } else {
              this.billList[index].list.push(res)
            }
          })
          console.log(JSON.parse(JSON.stringify(this.billList)))
          this.cooperativeUnitArr = this.billList.map((res) => {
            return {
              name: res.cooperativeUnit,
              id: res.cooperativeUnitId
            }
          })
          console.log(JSON.parse(JSON.stringify(this.cooperativeUnitArr)))
          this.sendersList = []
          let list2 = this.billDetails1.compensateList
          list2.forEach((val) => {
            let index = this.sendersList.findIndex(item => (item.cooperativeUnitId == val.cooperativeUnit))
            if (index == -1) {
              let arr = []
              arr.push(val)
              this.sendersList.push({ cooperativeUnit: val.cooperativeUnit, cooperativeUnitId: val.cooperativeUnitId, list: arr })
            } else {
              this.sendersList[index].list.push(val)
            }
          })
        }
      })
    },
    /**搜索条件单选选中*/
    setradio(data) {
      this.searchradio = JSON.stringify(data);
      this.companyId = data.firstPartyId;
      this.company = data.firstParty;
    },
    /**获取对应的搜索条件*/
    getsearchData() {
      let _this = this
      if (_this.currenindex == 2) {
        get_query_condition().then(res => {
          _this.cooperativeUnit = res.data.getCooperativeUnitlist.map(res => { return { name: res.cooperativeUnit, id: res.cooperativeUnitId } });
          _this.rawId = res.data.getRawList.map(res => { return { productName: res.rawName, id: res.rawId } });
        })
        get_supplier({settled:1}).then(res => {
          _this.contractId = res.data
        })
      }
      if (_this.currenindex == 1) {
        get_contract_list().then(res => {
          _this.searchData = res.data
        })
      }
      if (_this.currenindex == 3) {
        get_supplier({settled:0}).then(res => {
          _this.searchData = res.data
        })
      }
    },
    /**供应商选择*/
    submitsearch() {
      let text = JSON.parse(this.searchradio)
      this.tableParam.contractId = text.id
      this.tableParam.contractNo = text.contractNumber
      this.generate.clearingSourceId = text.clearingSourceId
      this.generate.supplier = text.supplierName
      this.generate.supplierId = text.supplierId
      this.searchText = text.contractNumber + '-' + text.supplierName
      cooperationqueryListsByPid({ supplierId: text.supplierId }).then((res) => {
        this.cooperativeUnit = res.data
      })
      this.stations = JSON.parse(text.stations)
      get_raw_list({ contractId: this.tableParam.contractId }).then(res => {
        this.rawId = res.data
      })
      this.tableParam.clearingSourceId = text.clearingSourceId
      this.tableParam.cooperativeUnitList = []
      this.tableParam.receiveStationIdList = []
      this.tableParam.rawIdList = []
      this.search = false
    },
    /**判断供应商和时间必传*/
    pagesgettableData() {
      if (((this.tableParam.contractId && this.tableParam.rawTypeId && this.datePicker && this.datePicker.length !== 0) && this.currenindex===1) ||((this.tableParam.contractId && this.datePicker && this.datePicker.length !== 0) && this.currenindex===2)) {
        this.gettableData()
        return
      }
      this.$message({
        message: '警告哦，请先选择供应商,原物料类型,时间段后查询',
        type: 'warning'
      });
    },
    /*导航栏切换*/
    choose(num) {
      this.currenindex = num;
    },
    /*重置查询条件*/
    init() {
      this.tableData = []
      if (this.currenindex == 3) {
        this.tableParam = { ...this.$options.data().tableParam, statementNo: "", supplierId: "" };
      } else {
        this.tableParam = { ...this.$options.data().tableParam, startTime: "", endTime: "", contractId: '', cooperativeUnitList: [], receiveStationIdList: [], rawIdList: [] };
        this.searchradio = ''
        this.cooperativeUnit = []
        this.stations = []
        this.rawId = []
        this.datePicker = []
        this.searchText = ''
      }
    },
    check3(name, index) {
      if (name == '结算合计') {
        this.billDetails1.totalList.forEach((v, k) => {
          if (index != k && v.cooperativeUnitId == this.billDetails1.totalList[index].cooperativeUnitId) {
            this.billDetails1.totalList[index].cooperativeUnitId = ''
            this.$message({
              message: '已存在当前选择开票单位！',
              type: 'warning'
            });
          }
        })
      }
    },
    check1(name, index) {
      if (name == '结算合计') {
        this.totalList.forEach((v, k) => {
          if (index != k && v.cooperativeUnitId == this.totalList[index].cooperativeUnitId) {
            this.totalList[index].cooperativeUnitId = ''
            this.$message({
              message: '已存在当前选择开票单位！',
              type: 'warning'
            });
          }
        })
      }
    },
    daYinTypeFun() {
      this.daYinType = true
      this.daYinForm = {...this.billDetails1, receivingUnit: '请选择'};
      let statementNum = 0, realPay = 0;
      this.daYinForm.totalList.forEach((v) => {
        statementNum = statementNum + Number(v.statementNum) | 0
        realPay = realPay + Number(v.realPay) | 0
      })
      this.daYinForm.statementNum = statementNum
      this.daYinForm.realPay = realPay
      this.daYinForm.realPay0 = this.digitUppercase(this.daYinForm.realPay)
    },
    /**打印*/
    doPrint() {
      if (!this.daYinForm.receivingUnit==='请选择') {
        this.$message({
          message: '请选择收货单位',
          type: 'warning'
        });
        return
      }
      // const style = '@page {margin:0mm}'//margin：0去掉页眉页脚，
      this.$print({
        // style,//设置边距
        printable: 'dyBox',
        type: 'html',
        maxWidth: 'auto',
        font_size: 'auto',
        targetStyles: ['*'],//必须保留样式
      })
    },
    digitUppercase(n) {
      let fraction = ['角', '分'];
      let digit = [
        '零', '壹', '贰', '叁', '肆',
        '伍', '陆', '柒', '捌', '玖'
      ];
      let unit = [
        ['元', '万', '亿'],
        ['', '拾', '佰', '仟']
      ];
      let head = n < 0 ? '欠' : '';
      n = Math.abs(n);
      let s = '';
      for (let i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
      }
      s = s || '整';
      n = Math.floor(n);
      for (let i = 0; i < unit[0].length && n > 0; i++) {
        let p = '';
        for (let j = 0; j < unit[1].length && n > 0; j++) {
          p = digit[n % 10] + unit[1][j] + p;
          n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
      }
      return head + s.replace(/(零.)*零元/, '元')
        .replace(/(零.)+/g, '零')
        .replace(/^整$/, '零元整');
    }
  },
};
</script>

<style lang="scss" scoped>
.dialoginfo {
  padding: 20px 20px 0 20px;
  max-height: 400px;
  overflow: auto;
}
.tabtop {
  width: 571px;
}
.el-input,
.el-select {
  width: 240px;
}
/*
 <el-link class="table_link" :underline="false">查看配合比</el-link>*/
.table_link {
  margin: 0 10px;
  color: $bg_color;
  cursor: pointer;
}

.table_link:hover {
  opacity: 0.5;
}
.bill_top {
  display: flex;
  justify-content: space-between;
  .text {
    font-weight: 600;
    color: #000;
  }
}
.bill_title {
  font-size: 18px;
  font-weight: 600;
  padding: 15px 0;
}
.bill_title1 {
  font-size: 18px;
  font-weight: 600;
  padding-top: 15px;
}
.bill_subtitle {
  padding: 20px 0;
  > span {
    padding-right: 20px;
  }
  .text {
    color: #000;
  }
}
.combined {
  border: 1px solid #ebeef5;
  text-align: center;
  line-height: 40px;
}

#dyBox {
  padding: 30px;
  > div {
    border: 1px solid #ccc;
    padding: 35px;
    .top {
      > div:nth-of-type(1) {
        font-size: 30px;
        font-weight: 800;
        text-align: center;
        letter-spacing: 35px;
        font-family: "LiSu";
      }
      > div:nth-of-type(2) {
        padding-top: 20px;
        padding-left: 335px;
        font-size: 14px;
        > div:nth-of-type(2) {
          margin-top: 20px;
          letter-spacing: 14px;
          > span {
            margin-left: 5px;
          }
        }
        span {
          letter-spacing: normal;
          display: inline-block;
          margin-left: 30px;
          font-size: 14px;
        }
      }
      > div:nth-of-type(3) {
        padding: 5px 0 5px 0;
        > span {
          font-size: 14px;
          width: 350px;
          display: inline-block;
        }
      }
    }
    .formBox {
      margin-top: 10px;
      > div {
        display: flex;
        > div {
          flex: 1;
          display: flex;
          margin-top: 30px;
          line-height: 10px;
          > .table {
            width: 110px;
            text-align: justify;
            span {
              display: inline-block;
              width: 100%;
            }
          }
          > span:nth-of-type(2) {
            text-align: center;
            margin-left: 5px;
            flex: 1;
            border-bottom: 1px solid #0a0a0a;
          }
        }
        > div:nth-of-type(1) {
          margin-right: 70px;
        }
      }
    }
    .tableBox {
      > div:nth-of-type(1) {
        margin-top: 70px;
        margin-bottom: 40px;
        font-size: 30px;
        font-weight: 800;
        text-align: center;
        letter-spacing: 35px;
        font-family: "LiSu";
      }
    }
  }
}
</style>

